package dao.impl;

import dao.BaseDao;
import dao.CollectionDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CollectionDaoImpl extends BaseDao implements CollectionDao {
    @Override
    public int add(int userId, int commId) {
        String sql = "insert into collection(user_id,commodity_id) values(?,?) ";
        return executeUpdate(sql,userId,commId);
    }

    @Override
    public boolean findExist(int userId, int commId) {
        String sql = "select * from collection where user_id=? and commodity_id=?";
        ResultSet rs = executeQuery(sql,userId,commId);
        try {
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    @Override
    public List<Integer> findCommIdByUserId(int userId,int startPage,int limit) {
        String sql = "select * from collection where user_id = ? limit ?,?";
        ResultSet rs = super.executeQuery(sql, userId,startPage,limit);
        List<Integer> list = new ArrayList<>();
        try {
            while(rs.next()){
                list.add(rs.getInt("commodity_id"));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int findCountByUserId(int userId) {
        String sql = "select count(*) from collection where user_id = ?";
        ResultSet rs = super.executeQuery(sql, userId);
        try {
            if(rs.next()){
                return rs.getInt(1);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return -1;
    }
}
